<?php


namespace App\Http\Controllers\WeChatPay;

use App\Models\Company;
use App\Models\MessageProduct;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\common\LMReturn;
use Yansongda\LaravelPay\Facades\Pay;
use App\Models\TopUp;

class WeChatPayController extends Controller
{
    // 短信充值产品查询
    public function SmsTopUpProduct(Request $request) {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $where = [
            'product_status' => 1
        ];
        $products = MessageProduct::where($where)->orderBy('message_product.price', 'asc')->get();
        $products_dic = json_decode($products, true);
        foreach ($products_dic as $k => $v) {
            $product_class = $v['product_class'];
            if ($product_class == 1) {
                $products_dic[$k]['product_class'] = '优惠套餐';
            } elseif ($product_class == 2) {
                $products_dic[$k]['product_class'] = '超值套餐';
            } else {
                $products_dic[$k]['product_class'] = '非正常套餐请勿付款';
            }
        }
        return LMReturn::Success($products_dic);
    }

    // 短信充值记录
    public function SmsTopUpRecord(Request $request) {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        $size = $all['size'] ?? 10;
        $company_id = env('COMPANY');
        $where = [
            'company_id' => $company_id,
        ];
        $top_ups = TopUp::where($where)
            ->whereIn('pay_status', [1, 2])
            ->with('message_product')
            ->orderBy('top_up.time', 'desc')
            ->paginate($size);
        $top_ups = json_decode(json_encode($top_ups), true);
        $data = $top_ups['data'];
        $return_data['current_page'] = $top_ups['current_page'];
        $return_data['to'] = $top_ups['to'];
        $return_data['total'] = $top_ups['total'];
        $return_data['last_page'] = $top_ups['last_page'];
        foreach ($data as $key => $value) {
            $data[$key]['time'] = date('Y-m-d H:i:s', strtotime($value['time']));
            if ($value['pay_status'] == 1) {
                $data[$key]['pay_status'] = '支付成功';
            } elseif ($value['pay_status'] == 2) {
                $data[$key]['pay_status'] = '未支付';
            } else {
                $data[$key]['pay_status'] = '支付失败';
            }
        }
        $return_data['data'] = $data;
        return LMReturn::Success($return_data);
    }

    // 短信充值接口
    public function SmsWeiChatScanPay(Request $request) {
        $all = $request->all();
        if (isset($all['product_id'])) {
            $product_id = $all['product_id'];
        } else {
            return LMReturn::Error('请选择产品');
        }
        $product = MessageProduct::find($product_id);
        if (empty($product)) {
            return LMReturn::Error('商品不存在');
        }
        if ($product->product_status != 1) {
            return LMReturn::Error('抱歉，该商品已下架');
        }
        $money = $product->price;
        $top_up = new TopUp();
        $company = env('COMPANY');
        $top_up->company_id = $company;
        $top_up->time = time();
        $top_up->product_id = $product_id;
        $top_up->pay_status = 2;
        $top_up->save();
        $out_trade_no = 'M'.time().$top_up->id;
        $top_up->out_trade_no = $out_trade_no;
        $top_up->save();
        $datas = [
            'out_trade_no'=>$out_trade_no,
            'body'=>'短信充值',
            'total_fee'=>$money*100,
        ];
        return Pay::wechat()->scan($datas);
    }

    public function NotifyCallback(Request $request)
    {
        try{
            $pay = Pay::wechat();
            $data = $pay->verify(); // 是的，验签就这么简单！
            $result_code = $data['result_code'];
            if ($result_code == 'SUCCESS') {
                $pay_status = 1;
                $remark = '支付成功';
            } else {
                $pay_status = 3;
                $remark = '支付失败';
            }
            $order_no = $data['out_trade_no'];
            $mch_id = $data['mch_id'];
            if ($mch_id != env('WECHAT_MCH_ID')) {
                return LMReturn::Error();
            }
            $total_fee = $data['total_fee'];
            $app_id = $data['appid'];
            if ($app_id != env('WECHAT_APP_ID')) {
                return LMReturn::Error();
            }
            if (strpos($order_no, 'M') !== false) {
                $order = TopUp::where('out_trade_no', $order_no)->with('message_product')->first();
                $money = $order->message_product->price;
                if ($total_fee != $money*100) {
                    return LMReturn::Error();
                }
                $count = $order->message_product->count;
                if ($pay_status == 1) {
                    $company = Company::find(env('COMPANY'));
                    $count_all = $company->count_all;
                    $company->count_all = $count_all + $count;
                    $company->save();
                }
                $order->pay_status = $pay_status;
                $order->remark = $remark;
                $order->save();
            }
            return $pay->success();
        } catch (\Exception $e) {
            return LMReturn::Error();
        }
    }
}
